package org.transmit;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;
import org.db.createdao.BaseDao;
import org.db.createdao.DaoPo;
import org.db.createdao.DatabaseUser;
import org.db.createsql.RealizeDaoInter;

public class ThreadDao {
	private static ThreadLocal<DaoPo> daos=new ThreadLocal<DaoPo>();
	private static Logger log = Logger.getLogger(ThreadDao.class);
	public static DaoPo getDaoPo(){
		DaoPo dao=daos.get();
		return dao;
	}
	/**
	 * 保存数据库连接
	 * @param con
	 */
	protected static void setDaoPo(Connection con){
		DaoPo dao=new DaoPo();
		dao.setCon(con);
		daos.set(dao);
	}
	/**
	 * 注入conn然后再返回.主要是处理定时器这块.或者其它特殊情况直接获得dao
	 * @param con
	 * @return
	 */
	public static RealizeDaoInter getDaoInter(){
		RealizeDaoInter rea=null;
		try {
			DaoPo dao=new DaoPo();
			dao.setCon(BaseDao.dao.getCon());
			daos.set(dao);//必须先添加到 ThreadLocal 才能再new对象.不然对象取不到conn
			rea=(RealizeDaoInter) Class.forName("org.db.createsql.AbstrDao"+BaseDao.dao.datacls).newInstance();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return rea;
	}
	
	/**
	 * 回滚数据库
	 */
	protected static void rollback(){
		try {
			daos.get().getCon().rollback();
		} catch (SQLException e) {
			log.error("回滚数据失败");
			e.printStackTrace();
		}
	}
	/**
	 * 提交数据
	 */
	public static void commit(){
		try {
			daos.get().getCon().commit();
		} catch (SQLException e) {
			log.error("提交数据失败...");
			e.printStackTrace();
		}
	}
	/**
	 * 关闭数据
	 */
	protected static void closedao(){
		DaoPo dao=daos.get();
		if(dao!=null){
			try {
				if(dao.getRs()!=null){
					dao.getRs().close();
				}
				if(dao.getPs()!=null){
					dao.getPs().close();
				}
				if(dao.getCon()!=null && !dao.getCon().isClosed()){
					dao.getCon().close();
				}
			} catch (SQLException e) {
				log.error("关闭连接错误");
				e.printStackTrace();
			}
		}
	}
}
